﻿using ReflectionStudio.Core.Events;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Globalization;
using System.Windows;
using WPFExcelReport.Helpers;
using INTEX.SCHEDULER;
using ReflectionStudio.Core.Events;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Windows;
using System.Data;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for EditEventWindow.xaml
    /// </summary>
    public partial class TFFSAV33
    {
        BackgroundWorker bgLoader;
        public TFFSAV33()
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            MV = new VICC_MKRF();
            DataContext = MV;
            IsAV = true;
            zAV33Height = 400;
            MESSAGES += "SSHOWGANT;";
            InitializeComponent();
            TMV.Scheduler = new DXAPS();
            TMV.SetUpAV33();
            bgLoader = new BackgroundWorker();
            bgLoader.DoWork += BgLoader_DoWork;
            bgLoader.RunWorkerCompleted += BgLoader_RunWorkerCompleted;
            TMV.OnMessage += TMV_OnMessage;
            IsEdit = false;
        }

        private void TMV_OnMessage(object sender, MessageEventArgs e)
        {
            TMV.INFO = e.Info.Details;
        }

        private void BgLoader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            IsBusy = false;
        }

        private void BgLoader_DoWork(object sender, DoWorkEventArgs e)
        {
            TMV.TAKEOVERSYT();

        }
        public override void EditCommand(object sender, RoutedEventArgs e)
        {
            base.EditCommand(sender, e);
        }

        public override void OnWorkflowIDChange(MessageEventArgs e)
        {
            MessageInfo msg = e.Info;
            string task = msg.MSGTYPE;
            switch (task)
            {
                case "SSHOWGANT":
                    if (zAV33Height >= 500)
                        zAV33Height = 400;
                    break;
            }
        }
        public override void bgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            base.bgWorker_RunWorkerCompleted(sender, e);
            vwMaster.View.MoveCurrentTo(-1);
            EventDispatcher.Instance.RaiseStatus("数据查询完成", StatusEventType.StopProgress);
        }



        private void ReSetTab()
        {
            IsAV = false;
        }


        TAVAFKS cAV;
        bool IsLoadMK = false;

        public override void QueryCommand(object sender, RoutedEventArgs e)
        {
            IsLoadMK = true;
            PM["KSTKRS"] = KSTKRS;
            PM["KST"] = KST;
            PM["AMTYP"] = AMTYP;
            PM["AGANG"] = AGANG;
            PM["MKFERLKZ"] = " ";
            LoadMKRF(PM);
            base.QueryCommand(sender, e);
        }
        private void LoadMKRF(Dictionary<string, object> pm)
        {
            switch (app.company)
            {
                default:
                    TMV.VKK.UVKK04(null);
                    break;
                case "SYT":

                    break;
            }
            dwData = TBMain.NewRow();
            dwData["ABFMANDANT"] = app.Mandant;
            dwData["ABFKSTKRS"] = pm["KSTKRS"].ToString();
            dwData["ABFKST"] = pm["KST"].ToString();
            dwData["ABFAGANG"] = pm["AGANG"].ToString();
            dwData["MKFERLKZ"] = pm["MKFERLKZ"].ToString();
            SResult = TMV.QTMKRF03(dwData);
            MergeData(SResult, true, true);
        }
        public override void OnSave()
        {
            if (!IsSaved)
                return;
            dwData = TBMain.NewRow();
            dwData["ABFMANDANT"] = dwMaster["ABFMANDANT"];
            dwData["ABFKSTKRS"] = dwMaster["ABFKSTKRS"];
            dwData["ABFKST"] = dwMaster["ABFKST"];
            dwData["ABFAGANG"] = dwMaster["ABFAGANG"];
            dwData["MKFERLKZ"] = dwMaster["MKFERLKZ"];
            dwData["ABAID"] = " AND ABAID='" + dwMaster["ABAID"].ToString() + "'";
            SResult = TMV.QTMKRF03(dwData);
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                dwMaster.ItemArray = row.ItemArray;
            }
            base.OnSave();
        }
        private void StartScheduleCommand(object sender, RoutedEventArgs e)
        {
            TMV.VKK.UVKK04(null);
            if (FTAUTOSPLIT)
            {
                if (cAV == null)
                {
                    cAV = new TAVAFKS();
                    cAV.KSTKRS = KSTKRS;
                    cAV.KST = KST;
                    cAV.AGANG = AGANG;
                    cAV.AMTYP = AMTYP;
                }
                cAV.StartReSplit();//先处理已经生产的任务
            }

            TMV.DXSchedule(KSTKRS, KST, AMTYP, LFD, AGANG);
        }

        private void ShowDetailCommand(object sender, RoutedEventArgs e)
        {
            TMV.ShowDetail(dwMKRF);
        }
        private void RefreshCommand(object sender, RoutedEventArgs e)
        {

        }
        private void TakeOverJobsCommand(object sender, RoutedEventArgs e)
        {
            IsBusy = true;
            bgLoader.RunWorkerAsync();
        }
        public override void OnManageChg()
        {
            base.OnManageChg();
            foreach (KeyValuePair<string, UIAM> kp in MachinesLib)
            {
                kp.Value.TMV.JJRULES = null;
                kp.Value.JJRules = null;
            }
        }

        private void WDCommand(object sender, RoutedEventArgs e)
        {
            Random random = new Random();
            int v = random.Next(1, 10);
            foreach (DataRow row in TBMain.Rows)
            {
                v = random.Next(0, 20);
                row["JP01"] = v;
                v = random.Next(8, 18);
                row["JP02"] = v * 10;
                
            }
        }

        private void YGCommand(object sender, RoutedEventArgs e)
        {
            //JP04
            Random random = new Random();
            int v = random.Next(1, 10);
            foreach (DataRow row in TBMain.Rows)
            {
                v = random.Next(0, 2); 
                row["JP04"] = v;
            }
        }

        private void PFCommand(object sender, RoutedEventArgs e)
        {
            //JP03
            Random random = new Random();
            int v = random.Next(1, 10);
            foreach (DataRow row in TBMain.Rows)
            {
                v = random.Next(1, 5);
                row["JP03"] = v;
            }
        }

        private void CGCommand(object sender, RoutedEventArgs e)
        {
            Random random = new Random();
            int v = random.Next(1, 10);
            foreach (DataRow row in TBMain.Rows)
            {
                v = random.Next(1, 3);
                row["JP06"] = v;
                v = random.Next(8, 10);
                row["JP05"] = row["JP05"].ToString().Substring(0,4) +Helper.Right("00"+v.ToString(),2)+ row["JP05"].ToString().Substring(6, 2);
            }
           
            //JP06
        }

        private void RSCommand(object sender, RoutedEventArgs e)
        {
            foreach (DataRow row in TBMain.Rows)
            {
                row["JP01"] = 0;
                row["JP02"] = 0;
                row["JP03"] = 0;
                row["JP04"] = 0;
                row["JP05"] = row["JP05"].ToString().Substring(0, 4) +"08"+ row["JP05"].ToString().Substring(6, 2);
                row["JP06"] = 0; 
            }
        }
        private void SVCommand(object sender, RoutedEventArgs e)
        {
            TMV.SaveTask(TMV.SetProd);
        }
    }
    public partial class VICC_MKRF
    {
        public DataSet PageLoad(DataRow dwData)
        {
            DataSet Set = new DataSet();
            int idx = 0;
            int rows = 200;
            while (true)
            {
                SResult = QSYTFF(dwData, idx, rows);
                if (SResult.Tables[0].Rows.Count == 0)
                    break;
                Set.Merge(SResult);
                idx++;
                if (idx > 400)
                    break;
            }
            return Set;

        }

        public DataSet QABPNO(DataRow dwData)
        {
            or1 = OracleDB.CreateCommand();
            or1.CommandText = "SELECT DISTINCT JP34 || '           ' || ';' || ABPART AS KEY, ABFAUFKRS|| ABFAUFLFD || ABFAUFPOS AS ORDERNO FROM ICC_MKRF";
            or1.CommandText = INTEXDBC.InjectData(or1.CommandText, dwData);
            SResult = Connect2Proxy(or1);
            SResult.Tables[0].TableName = TableName;
            return SResult;
        }
        public DataSet QSYTFF(DataRow dwData, int idx, int rows)
        {
            SqlCommand SQLCmd;
            SQLCmd = SqlServerDB.CreateCommand();
            string sql = GETAFS(dwData);
            SQLCmd.CommandText = "select * from ( select row_number() over(order by SUBSTRING(FN_CARD,2,8)+STEP_NO) as rownumber, " + sql + " ) A where rownumber < " + (idx + 1) * rows + " AND rownumber >= " + idx * rows;
            SResult = Connect2Proxy(SQLCmd);
            SResult.Tables[0].TableName = TableName;
            return SResult;
        }
        public string GETAFS(DataRow dwData)
        {
            string sql = " * FROM VIEW_GETPRODUCEINFO";
            sql = INTEXDBC.InjectData(sql, dwData);
            return sql;
        }

        public void TAKEOVERSYT()
        {
            Dictionary<String, string> pd = new Dictionary<string, string>();
            dwData = TBMain.NewRow();
            SResult = QABPNO(dwData);
            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                pd[row["KEY"].ToString()] = row["ORDERNO"].ToString();
            }
            dwData = TBMain.NewRow();
            SetUpNewRow(ref dwData);
            SResult = PageLoad(dwData);
            CALL = SResult.Tables[0].Rows.Count;

            foreach (DataRow row in SResult.Tables[0].Rows)
            {
                CNOW++;
                try
                {
                    RaiseMessage(CNOW + "/" + CALL + " 转入");
                    string pdpz = row["JOB_NO"].ToString().PadRight(20) + ";" + Helper.Left(row["GF_NO"].ToString().PadRight(20), 20);
                    string order = "";
                    if (pd.ContainsKey(pdpz))
                    {
                        order = pd[pdpz];
                    }
                    else
                    {
                        KRS = pdpz.Substring(0, 2);
                        LFD = "00" + pdpz.Substring(2, 4);
                        POS = VSDDAT.SD22.GETNEXT("0022", KRS, LFD, 1, 3, 8);
                        order = KRS + LFD + POS;
                        pd[pdpz] = order;
                    }
                    dwData["ABFAUFKRS"] = order.Substring(0, 2);
                    dwData["ABFAUFLFD"] = order.Substring(2, 6);
                    dwData["ABFAUFPOS"] = order.Substring(8, 3);
                    dwData["JP34"] = row["JOB_NO"].ToString();
                    //ABPKDPARTIE
                    dwData["MKFSME"] = 2;
                    dwData["MKFTP"] = row["FN_CARD"].ToString().PadRight(9).Substring(5, 4);
                    dwData["ABAID"] = row["FN_CARD"].ToString() + "_" + row["STEP_NO"].ToString();
                    dwData["MKFSMG2"] = double.Parse(row["QUANTITY"].ToString()) * 100;
                    dwData["ABFAFOLGE"] = Helpers.Helper.Right("000" + row["STEP_NO"].ToString(), 3);
                    //dwData[""] = row["机台"];
                    string speed = row["SPEED"].ToString();
                    if (speed == "")
                        speed = "9999";
                    dwData["ABFBASMGE"] = double.Parse(speed) * 100;

                    dwData["ABFSOLLMG"] = double.Parse(row["JOB_QTY"].ToString()) * 100;
                    dwData["ABFSTATUS"] = " ";
                    if (row["P_STATUS"].ToString() == "Y")
                    {
                        dwData["ABFSTATUS"] = "R";
                    }
                    dwData["ABPART"] = Helper.Left(row["GF_NO"].ToString().PadRight(20), 20);
                    string chg = "2016-5-14 7L30:00";
                    int midx = -1;
                    chg = row["DELIVERY_DATE"].ToString();
                    DateTimeFormatInfo dtFormat = new DateTimeFormatInfo();
                    dtFormat.ShortDatePattern = "yyyy/MM/dd";
                    midx = -1;
                    midx = chg.IndexOf(' ');

                    chg = chg.Substring(0, midx).Replace('-', '/');
                    DateTime chgtime = Convert.ToDateTime(chg, dtFormat);
                    Helper.GetStdDate(ref date, ref time, chgtime);
                    dwData["JP05"] = date;
                    dwData["ABFSOLLDAT"] = date;
                    //dwData["VKPEND"] = date;
                    dwData["ABFKSTKRS"] = "  ";
                    dwData["ABFKST"] = "0600";
                    if (row["MACHINE_MODEL_CHN"].ToString().Contains("定型"))
                    {
                        dwData["ABFAGANG"] = "FX".PadRight(15);
                    }
                    if (row["MACHINE_MODEL_CHN"].ToString().Contains("定型"))
                    {
                        dwData["ABFAGANG"] = "FX".PadRight(15);
                    }
                    if (row["MACHINE_MODEL_CHN"].ToString().Contains("定型"))
                    {
                        dwData["ABFAGANG"] = "FX".PadRight(15);
                    }
                    if (row["MACHINE_MODEL_CHN"].ToString().Contains("定型"))
                    {
                        dwData["ABFAGANG"] = "FX".PadRight(15);
                    }
                    if (row["MACHINE_MODEL_CHN"].ToString().Contains("定型"))
                    {
                        dwData["ABFAGANG"] = "FX".PadRight(15);
                    }
                    //dwData["ABPBESCHICH"] = row["整理方式"];
                    dwData["JP30"] = row["CAR_NO"];
                    dwData["JP31"] = Helper.ConvertGB2312To8859P1(row["MACHINE_MODEL_CHN"].ToString());
                    string finish = row["FINISHING_METHOD"].ToString();
                    int idx = -1;
                    idx = finish.IndexOf("-");
                    string left = "";
                    string right = "";
                    if (idx > 0)
                    {
                        left = finish.Substring(0, idx);
                        right = finish.Substring(idx).Replace("--", "");
                        dwData["ABPBESCHICH"] = Helper.Left(left.PadRight(10), 10);
                    }
                    dwData["JP32"] = Helper.ConvertGB2312To8859P1(row["FINISHING_METHOD"].ToString());
                    dwData["ABKKDAUFTNR"] = Helper.Left(row["PPO_NO"].ToString().PadRight(20), 20);
                    dwData["JP33"] = Helper.ConvertGB2312To8859P1(row["COMBO"].ToString());
                    DMKRF01(dwData);
                    BATCHWB14(dwData);
                }
                catch (Exception ex)
                {
                    RaiseMessage(row["FN_CARD"].ToString() + "." + row["STEP_NO"].ToString() + "转换出现错误");
                    LogHelper.error(ex.Message);
                }

            }
            POSTCHG();
        }
    }
}